/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * chatSERIAL.java
 *
 * Created on 10/04/2012, 09:33:04 PM
 */

package Vista;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import comunicacion.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.StringTokenizer;
import javax.swing.JFileChooser;

/**
 *
 * @author Baculima
 */
public class chatSERIAL extends javax.swing.JFrame {

    /** Creates new form chatSERIAL */
    InputStream in;
    OutputStream out;
       String nombre;
       String nomLog;
       String nomArch;
       File archivo;
       double tamArch;
       boolean bandArch=false;
    public chatSERIAL() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtconversa = new javax.swing.JTextArea();
        cmdenviar = new javax.swing.JButton();
        txtenviar = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        lblConectado = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblYo = new javax.swing.JLabel();
        cmdEnviar = new javax.swing.JButton();
        Progreso = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("CHAT - PUERTO SERIAL RS232");

        txtconversa.setColumns(20);
        txtconversa.setRows(5);
        jScrollPane1.setViewportView(txtconversa);

        cmdenviar.setText("ENVIAR");
        cmdenviar.setEnabled(false);
        cmdenviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdenviarActionPerformed(evt);
            }
        });

        txtenviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtenviarActionPerformed(evt);
            }
        });
        txtenviar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtenviarKeyPressed(evt);
            }
        });

        jButton1.setText("CONECTAR");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setText("Conectados:");

        cmdEnviar.setText("Enviar Archivo");
        cmdEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdEnviarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(63, 63, 63)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtenviar, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(cmdenviar))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmdEnviar)
                                .addGap(18, 18, 18)
                                .addComponent(Progreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblYo)
                            .addComponent(jButton1)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblConectado)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3)))))
                .addContainerGap(81, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(jLabel1)
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(7, 7, 7)
                        .addComponent(lblYo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblConectado))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtenviar, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmdenviar))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cmdEnviar)
                    .addComponent(Progreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtenviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtenviarActionPerformed
        // TODO add your handling code here:





    }//GEN-LAST:event_txtenviarActionPerformed

    private void txtenviarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtenviarKeyPressed
        // TODO add your handling code here
        
        if (evt.getKeyCode()==10)
            cmdenviar.doClick();
          
       

    }//GEN-LAST:event_txtenviarKeyPressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
    //cuando se presiona el boton conectar pide un nombre para login
       nombre=JOptionPane.showInputDialog("INGRESE SU NOMBRE DE LOGGIN");
       //System.out.print(nombre);


       try {//abre el puerto para la comunicacion
            Comunicacion comm1=new Comunicacion();
            comm1.connect("COM3");
            this.in=comm1.in;
            this.out=comm1.out;
            (new Thread(new SerialReader(in))).start();//inicia el hilo para esperar lectura
           nomLog="$$Log#"+nombre;//envia el nombre de loggin
            cmdenviar.setEnabled(true);
            enviarMensaje(nomLog);
            lblYo.setText(nombre);

        } catch (Exception e) {

            e.printStackTrace();
        }
       

    }//GEN-LAST:event_jButton1ActionPerformed

    private void cmdenviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdenviarActionPerformed
        // TODO add your handling code here:
        String cadena=nombre+" dice: "+txtenviar.getText();//anexa el nombre de loggin y envia el mensaje
        enviarMensaje(cadena);
        txtconversa.setText(txtconversa.getText()+"\n"+cadena);

    }//GEN-LAST:event_cmdenviarActionPerformed

    private void cmdEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdEnviarActionPerformed
        // TODO add your handling code here:
        
        
    }//GEN-LAST:event_cmdEnviarActionPerformed
     public class SerialReader implements Runnable { //hilo prara lectura

        InputStream in;

        public SerialReader(InputStream in) {
            this.in = in;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            int len = -1;
            try {
            String mensaje="";
            String cadena="";
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Conversion_archivos conv = new Conversion_archivos();
            boolean band=true;//mietras haya bits en el buffer los anexa en una cadena
                while ((len = this.in.read(buffer)) > -1) {
                    mensaje=(new String(buffer, 0, 1)); 
                    System.out.println(mensaje);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new chatSERIAL().setVisible(true);
            }
        });
    }
    private void enviarMensaje(String cadena)
    {
        
        char [] mensj=cadena.toCharArray();//transfrma el string a cadena de chars 
        //para  luego transformarla en enteros y mandar por el puerto
        byte c=0;
        int ln=mensj.length;
        for(int i=0;i<ln;i++)
        {
            try {
                c = (byte) mensj[i];
                this.out.write(c);//envia la cadena byte por byte
            } catch (IOException ex) {
                Logger.getLogger(chatSERIAL.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JProgressBar Progreso;
    private javax.swing.JButton cmdEnviar;
    private javax.swing.JButton cmdenviar;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblConectado;
    private javax.swing.JLabel lblYo;
    private javax.swing.JTextArea txtconversa;
    private javax.swing.JTextField txtenviar;
    // End of variables declaration//GEN-END:variables

}
